import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from '@/config';
import { ISession } from '@/pages/api';
import { prepareConnection } from '@/db';
import { Tag, User } from '@/db/entity';
import { EXCEPTION_USER, EXCEPTION_TAG } from '@/pages/api/config/codes';

const follow = async (req: NextApiRequest, res: NextApiResponse) => {
  const session: ISession = req.session;
  const { tagId, type } = req?.body || {};
  const db = await prepareConnection();
  const tagRepo = db.getRepository(Tag);
  const userRepo = db.getRepository(User);

  const user = await userRepo.findOne({
    where: {
      id: session.userId,
    }
  })

  const tag = await tagRepo.findOne({
    where: {
      id: tagId,
    },
    relations: ['users']
  })

  if (!user) {
    res?.status(200).json({
      ...EXCEPTION_USER?.NOT_LOGIN,
    });
    return;
  }

  if (tag?.users) {
    if (type === 'follow') {
      tag.users = [...tag.users, user];
      tag.follow_count += 1;
    } else if (type === 'unfollow') {
      tag.users = tag.users.filter((item) => item.id !== user.id);
      tag.follow_count -= 1;
    }
  }

  if (tag) {
    const resTag = await tagRepo.save(tag)

    res.status(200).json({
      code: 200,
      msg: 'success',
      data: resTag
    })
  } else {
    res?.status(200)?.json({
      ...EXCEPTION_TAG?.FOLLOW_FAILED,
    });
  }
}

export default withIronSessionApiRoute(follow, ironOptions)